﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GooNews.ViewModels;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Devices;
using AgiliTrain.Phone.Utilities.EventArgs;
using System.Threading;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.IO;
using System.Diagnostics;

namespace GooNews.Controls
{
  /// <summary>
  /// 
  /// </summary>
  public partial class NewsItemControl : UserControl
  {
    public NewsItemControl()
    {
      InitializeComponent();

      // Hack to stop tapping from propogating to ListBox
      GestureService.GetGestureListener(itemContext).Tap += (s, e) => e.Handled = true;

      // Handle Events for Menu Items of Context Menu
      shareEmailMenuItem.Click += new RoutedEventHandler(shareEmailMenuItem_Click);
      instaMenuItem.Click += new RoutedEventHandler(instaMenuItem_Click);

      // Disable Menu Item if InstaPaper isn't registered
      instaMenuItem.IsEnabled = App.ViewModel.Options.AllowInstaPaper;

      //Loaded += (s, e) => LoadImage();
    }

    /// <summary>
    /// Loads the image.
    /// </summary>
    void LoadImage()
    {
      if (DataContext != null)
      {
        var item = (FeedItem)DataContext;
        if (item.HasImageUrl)
        {
          ThreadPool.QueueUserWorkItem(img =>
          {
            var request = HttpWebRequest.CreateHttp((string)img);
            request.BeginGetResponse(r =>
            {
              try
              {
                var res = request.EndGetResponse(r);
                var stream = res.GetResponseStream();
                var memory = new MemoryStream((int)res.ContentLength);

                byte[] rgb = new byte[1024];
                int cb;

                while ((cb = stream.Read(rgb, 0, rgb.Length)) > 0)
                {
                  memory.Write(rgb, 0, cb);
                }

                memory.Position = 0;
                if (memory.Length > 0)
                {
                  SmartDispatcher.BeginInvoke(() =>
                    {
                      var src = new BitmapImage();
                      src.SetSource(memory);
                      theImage.Source = src;
                    });
                }
                else
                {
                  Debug.WriteLine("Found empty response stream.");
                }
              }
              catch
              {
                // Couldn't get the image so punt
                Debug.WriteLine("Exception thrown while reading image.");
              }
            }, null);
          }, item.ImageUrl);
        }
      }
    }

    /// <summary>
    /// Handles the Click event of the instaMenuItem control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    void instaMenuItem_Click(object sender, RoutedEventArgs e)
    {
      App.DoHaptic();
      var item = DataContext as FeedItem;
      if (item != null)
      {
        item.SendToInstaPaper(r =>
          {
            if (r)
            {
              RaiseMessageSent("Added to InstaPaper");
            }
            else
            {
              RaiseMessageSent("Failed to add to InstaPaper");
            }
          });
      }
    }

    /// <summary>
    /// Occurs when [message sent].
    /// </summary>
    public event EventHandler<MessageEventArgs> MessageSent;

    /// <summary>
    /// Raises the message sent.
    /// </summary>
    /// <param name="msg">The MSG.</param>
    void RaiseMessageSent(string msg)
    {
      if (MessageSent != null) MessageSent(this, new MessageEventArgs(msg));
    }

    /// <summary>
    /// Handles the Click event of the shareEmailMenuItem control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
    void shareEmailMenuItem_Click(object sender, RoutedEventArgs e)
    {
      App.DoHaptic();
      var item = DataContext as FeedItem;
      if (item != null)
      {
        item.SendToEmail();
      }
    }

    /// <summary>
    /// Handles the Tap event of the GestureListener control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="Microsoft.Phone.Controls.GestureEventArgs"/> instance containing the event data.</param>
    private void GestureListener_Tap(object sender, Microsoft.Phone.Controls.GestureEventArgs e)
    {
      var item = DataContext as FeedItem;
      if (item != null)
      {
        App.ViewModel.NavigateToFeed(item);
      }
    }
  }
}
